/*
 * Copyright (c) 2010 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.fdaoud.rayures.quickstart;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.Map;

public class SimpleTemplateEngine {

  public void write(InputStream inputStream, Map<String, Object> dataModel, Writer writer)
    throws Exception
  {
    BufferedReader input = new BufferedReader(new InputStreamReader(inputStream));
    BufferedWriter output = new BufferedWriter(writer);

    String line = null;

    while ((line = input.readLine()) != null) {
      int start = line.indexOf("${");
      int end = line.indexOf("}");

      if (start != -1) {
        if (end == -1) {
          throw new IllegalArgumentException("Line has ${ but no }: " + line);
        }
        String var = line.substring(start + 2, end);
        Object value = dataModel.get(var);

        if (value != null) {
          if (end == line.length() - 1) {
            line = line.substring(0, start) + value;
          }
          else {
            line = line.substring(0, start) + value + line.substring(end + 1);
          }
        }
      }
      output.write(line);
      output.newLine();
    }
    output.flush();
  }
}
